# -*- coding: utf-8 -*-
import json
import os

from fastapi import Request
from pydantic import BaseModel

from schemas.response_entity import JsonModel
from configs import ROOT_PATH

PROMPTS_FILE = os.path.join(ROOT_PATH, "configs", "json_files", "prompts.json")
KB_CHAT_TEMPLATE = "KB_CHAT_TEMPLATE"


class UpdatePromptEntity(BaseModel):
    content: str


async def update_prompt(request: Request, payload: UpdatePromptEntity):
    user = request.state.user
    if not user.check_admin_role():
        return JsonModel(code=401, data=None, msg=f"用户无权限").to_response()

    try:
        # 读旧内容（若不存在则初始化空字典）
        data = {}
        if os.path.exists(PROMPTS_FILE):
            try:
                with open(PROMPTS_FILE, 'r', encoding='utf-8') as f:
                    data = json.load(f) or {}
            except Exception:
                data = {}

        # 写入新内容
        data[KB_CHAT_TEMPLATE] = payload.content
        os.makedirs(os.path.dirname(PROMPTS_FILE), exist_ok=True)
        with open(PROMPTS_FILE, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

        return JsonModel(code=200, data=None, msg="更新成功").to_response()
    except Exception as e:
        return JsonModel(code=500, data=None, msg=f"更新失败: {e}").to_response()


async def read_prompt(request: Request, token: str):
    user = request.state.user
    if not user.check_admin_role():
        return JsonModel(code=401, data=None, msg=f"用户无权限").to_response()

    try:
        # 读旧内容（若不存在则初始化空字典）
        data = {}
        if os.path.exists(PROMPTS_FILE):
            try:
                with open(PROMPTS_FILE, 'r', encoding='utf-8') as f:
                    data = json.load(f) or {}
            except Exception:
                data = {}

        # 写入新内容
        prompt = data[KB_CHAT_TEMPLATE]
        return JsonModel(code=200, data={"prompt": prompt}, msg="读取成功").to_response()

    except Exception as e:
        return JsonModel(code=500, data=None, msg=f"读取失败: {e}").to_response()


